package com.example.androidexp22


import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

private const val SHARED_PREFS_NAME = "com.example.androidexp22_preferences"
private const val KEY_DATES = "saved_dates"

class DateChoose : AppCompatActivity() {
    data class Event(
        val date: String,
        val calories: Int
    ) : Parcelable {
        constructor(parcel: Parcel) : this(
            parcel.readString() ?: "",
            parcel.readInt()
        )

        override fun writeToParcel(parcel: Parcel, flags: Int) {
            parcel.writeString(date)
            parcel.writeInt(calories)
        }

        override fun describeContents(): Int = 0

        companion object CREATOR : Parcelable.Creator<Event> {
            override fun createFromParcel(parcel: Parcel): Event = Event(parcel)
            override fun newArray(size: Int): Array<Event?> = arrayOfNulls(size)
        }

    } //存放数据的类，Parcelable是为了更好的在各个Activity中传输数据
    private lateinit var addButton1: Button
    private lateinit var recyclerView: RecyclerView
    private val dataList = mutableListOf<Event>()
    private fun setupRecyclerView() { //按下按钮跳转界面
        recyclerView.adapter = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_date, parent, false)
                return ViewHolder(view)
            }
            override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
                val event = dataList[position]
                (holder as ViewHolder).bind(event)
            }

            override fun getItemCount(): Int = dataList.size

            inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
                private val textViewDate = itemView.findViewById<TextView>(R.id.textViewDate)
                private val textViewCalories = itemView.findViewById<TextView>(R.id.textViewCalories)

                fun bind(event: Event) {
                    textViewDate.text = event.date
                    textViewCalories.text = ":   ${event.calories} "
                }
            }
        }
    }

    private fun saveDatesToSharedPreferences(context: Context, events: List<Event>) {  //永久保存数据在虚拟机中
        val sharedPreferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        val serializedEvents = events.joinToString("\n") { "${it.date},${it.calories}" }
        editor.putString(KEY_DATES, serializedEvents)
        editor.apply()
    }

    private fun getSavedEventsFromSharedPreferences(context: Context): List<Event> {   //永久获取数据
        val sharedPreferences = context.getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE)
        val savedEventsStr = sharedPreferences.getString(KEY_DATES, "") ?: ""
        return savedEventsStr.split("\n").filter { it.isNotBlank() }
            .mapNotNull {
                val parts = it.split(",")
                if (parts.size == 2) {
                    Event(parts[0], parts[1].toIntOrNull() ?: 0)
                } else null
            }
    }
    private fun parseAndFormatDate(dateStr: String?): String? {  //格式转化
        if (dateStr == null) return null
        val inputFormat = SimpleDateFormat("dd/MM/yyyy") // 假设原始日期格式为"dd/MM/yyyy"
        return try {
            val date = inputFormat.parse(dateStr)
            SimpleDateFormat("yyyy-MM-dd").format(date) // 转换为目标格式"yyyy-MM-dd"
        } catch (e: ParseException) {
            println("日期转换错误: ${e.message}")
            null
        }
    }
    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    private fun updateOrAddEvent(event: Event) {
        val existingEventIndex = dataList.indexOfFirst { it.date == event.date }
        if (existingEventIndex != -1) {
            // 如果找到匹配的日期，更新卡路里
            dataList[existingEventIndex] = event.copy(calories = event.calories)
        } else {
            // 否则，添加新事件
            dataList.add(event)
        }
        // 更新UI
        recyclerView.adapter?.notifyDataSetChanged()
    }

    private fun sendDataBack() { //与MainActivity建立联系
        val intent = Intent()
        intent.putParcelableArrayListExtra("calorie_events", ArrayList(dataList))
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化控件
        setContentView(R.layout.datechoose)
        addButton1 = findViewById(R.id.add_button)
        recyclerView = findViewById(R.id.calorie_recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        dataList.addAll(getSavedEventsFromSharedPreferences(this))
        setupRecyclerView()
//        dataList.clear()//该函数只是为了清理RecycleView中的数据.
        addButton1.setOnClickListener {
            sendDataBack()
            saveDatesToSharedPreferences(this, dataList)
            val intent = Intent(this, EventDetailsActivity::class.java)
            intent.putParcelableArrayListExtra("events_data", ArrayList(dataList) as ArrayList<Parcelable>)
            startActivity(intent)
        }

//        dataList.addAll(getSavedEventsFromSharedPreferences(this)) // 将已保存的日期先加载到 dataList
        // 接收并转换新传入的日期和卡路里
        val originalDateString = intent.getStringExtra("selected_date")
        val receivedCalories = intent.getIntExtra("selected_calories", 0)
        val parsedDate = parseAndFormatDate(originalDateString)
        if (parsedDate != null && receivedCalories > 0) {
            val newEvent = Event(parsedDate, receivedCalories)
            updateOrAddEvent(newEvent)
        } else {
            showToast("未接收到有效的日期或卡路里数据")
        }
    }


}